import base64
import json
from json import JSONDecodeError

import faker
from locust import FastHttpUser, task, run_single_user, constant, tag

index_cookie = 2000
fake = faker.Faker()

def get_cookie():
    global index_cookie
    index_cookie += 1
    l = []
    with open('../cookie.txt', mode='r', encoding='utf8') as f:
        for account in f:
            l.append(account.strip())
        return str(l[index_cookie])


def enconde_bs64(data):
    data = json.dumps(data)
    encode64 = base64.b64encode(data.encode('utf-8'))
    return encode64.decode('utf-8')


def decode64_str(data):
    decode64 = base64.b64decode(data)
    decode64_str = decode64.decode('utf-8')
    return decode64_str


class MemoTask(FastHttpUser):
    host = "https://www.retone-hearing.fit"
    wait_time = constant(1)
    # header = {"Content-Type": "application/json"}
    cookie = get_cookie()
    # default_headers = {"Content-Type": "application/json"}
    def on_start(self):
        numbers_of_user = False
        if numbers_of_user == True:
            self.header = {"Cookie": f"hearingaid_user={get_cookie()}",
                           "Content-Type": "application/json"}
        else:
            self.header = {"Cookie": f"hearingaid_user={self.cookie}",
                           "Content-Type": "application/json"}

    @task
    @tag('modify')
    def modify_moemo(self):
        global index_cookie
        get_id_url = '/platformRetoneFit/api/memo/needAppUserAuth/responseEncode/requestDecode/getAllMemo'
        with self.rest('post', get_id_url, headers=self.header, name="modify_getall") as resp:
            try:
                if resp.status_code > 400 or (resp.json()['data'] == None and resp.json()['description'] != None):
                    resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
                else:
                    resp_data = json.loads(decode64_str(resp.json()['data']))
                    info = {
                        "memoId": resp_data[0]['memoId'],
                        "note": fake.address(),
                        "activeTime": "2021-05-07 01:12:12",
                        "memoTypeEnum": "DAY_OF_WEEK",
                        "dayOfWeeks": [
                            "THURSDAY",
                            "WEDNESDAY",
                            "FRIDAY"
                        ]
                    }
                    url = '/platformRetoneFit/api/memo/needAppUserAuth/responseEncode/requestDecode/modifyMemo'
                    with self.rest('post', url, data=enconde_bs64(info), headers=self.header) as resp:
                        if resp.status_code > 400 or (
                                resp.json()['data'] == None and resp.json()['description'] != None):
                            resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
                        else:
                            resp.success()
            except JSONDecodeError:
                resp.failure("Response could not be decoded as JSON")
            except KeyError:
                resp.failure("Response did not contain expected key 'data'")


if __name__ == '__main__':
    run_single_user(MemoTask)